package org.tong.net;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class ListenThread extends SelectorThread {

    private static final Logger logger = LoggerFactory.getLogger(ListenThread.class);


    public ListenThread() throws IOException {

    }

    @Override
    void handleSelectionKey(SelectionKey selectionKey) {
        switch (selectionKey.readyOps()) {
            case SelectionKey.OP_ACCEPT: {
                ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
                try {
                    logger.debug("receive a connection");
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    handlerSocketChannel(socketChannel);
                } catch (IOException e) {
                    logger.error("error :" + e.getMessage());
                } finally {
                    try {
                        serverSocketChannel.register(this.getSelector(), SelectionKey.OP_ACCEPT);
                    } catch (ClosedChannelException e) {
                        logger.error("register error:" + e.getMessage());
                    }
                }
            }
            break;
            default:
                logger.error("not support ops:" + selectionKey.readyOps());
        }
    }

    private void handlerSocketChannel(SocketChannel socketChannel) {


    }
}
